package org.sfans.website.config;

import java.net.URL;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.sfans.core.Constants;
import org.sfans.core.domain.Website;
import org.sfans.core.domain.WebsiteRepository;
import org.sfans.core.web.exception.ResourceNotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

@Profile("web")
@Component
public class WebsiteInterceptor extends HandlerInterceptorAdapter {

	private static final Logger LOG = LoggerFactory.getLogger(WebsiteInterceptor.class);

	@Autowired
	private WebsiteRepository repository;

	@Override
	public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response,
			final Object handler) throws Exception {
		final String url = request.getRequestURL().toString();
		final String host = new URL(url).getHost();
		final Website website = repository.findByHostsIn(host)
				.orElseThrow(() -> new ResourceNotFoundException(
						String.format("No website found for host name: %s", host)));

		request.setAttribute(Constants.WEBSITE_ATTRIBUTE_NAME, website);

		LOG.debug("Website: {} detected for URL:[{}]", website, url);
		
		return true;
	}

}
